/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.DataImplRpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021/8/10
 * @description:
 */
@RestController
@RequestMapping(value = "/je/develop/dataImpl")
public class DataImplController extends AbstractPlatformController {

    @Autowired
    private DataImplRpcService dataImplRpcService;

    /**
     * 生成模版并且返回地址
     *
     * @param param
     */
    @RequestMapping(value = "generateTemplate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult generateTemplate(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = param.getPkValue();
        JSONObject returnObj = new JSONObject();
        try {
            returnObj = dataImplRpcService.generateTemplate(pkValue, new ArrayList<>(), returnObj);
            return BaseRespResult.successResult(returnObj.getString("templatePath"));
        } catch (Exception e) {
            e.printStackTrace();
            return BaseRespResult.errorResult("旧版导入工具导出模版异常");
        }
    }

    /**
     * 导入字段
     *
     * @param param
     */
    @RequestMapping(value = "implFields", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult implFields(BaseMethodArgument param,HttpServletRequest request) {
        String pkValue = param.getPkValue();
        String funcId = request.getParameter("funcId");
        metaService.executeSql("DELETE FROM JE_SYS_DATAFIELD WHERE JE_SYS_DATATEMPLATE_ID={0}", pkValue);
        //AND RESOURCECOLUMN_XTYPE!='morecolumn'
        List<DynaBean> columnFields = metaService.select("JE_CORE_VCOLUMNANDFIELD",
                ConditionsWrapper.builder().apply("RESOURCECOLUMN_FUNCINFO_ID={0}  ORDER BY SY_ORDERINDEX", funcId));
        for (DynaBean columnField : columnFields) {
            DynaBean dataField = new DynaBean("JE_SYS_DATAFIELD", false);
            dataField.set(BeanService.KEY_PK_CODE, "JE_SYS_DATAFIELD_ID");
            dataField.set("SY_ORDERINDEX", columnField.getStr("SY_ORDERINDEX"));
            dataField.set("DATAFIELD_CODE", columnField.getStr("RESOURCECOLUMN_CODE"));
            dataField.set("DATAFIELD_NAME", columnField.getStr("RESOURCECOLUMN_NAME"));
            if ("morecolumn".equals(columnField.getStr("RESOURCECOLUMN_XTYPE"))) {
                dataField.set("DATAFIELD_XTYPE", "morecolumn");
            } else if ("rownumberer".equals(columnField.getStr("RESOURCECOLUMN_XTYPE"))) {
                dataField.set("DATAFIELD_XTYPE", "rownumberer");
            } else if ("uxcheckcolumn".equals(columnField.getStr("RESOURCECOLUMN_XTYPE"))) {
                dataField.set("DATAFIELD_XTYPE", "cbbfield");
                dataField.set("DATAFIELD_CONFIGINFO", columnField.getStr("RESOURCEFIELD_CONFIGINFO"));
            } else if ("datefield".equals(columnField.getStr("RESOURCECOLUMN_XTYPE")) || ("datetimefield".equals(columnField.getStr("RESOURCECOLUMN_XTYPE")))) {
                dataField.set("DATAFIELD_XTYPE", columnField.getStr("RESOURCEFIELD_XTYPE"));
            } else {
                String xtype = columnField.getStr("RESOURCEFIELD_XTYPE");
                if (ArrayUtils.contains(new String[]{"cbbfield", "rgroup", "cgroup"}, xtype)) {
                    dataField.set("DATAFIELD_XTYPE", "cbbfield");
                    dataField.set("DATAFIELD_CONFIGINFO", columnField.getStr("RESOURCEFIELD_CONFIGINFO"));
                } else if (ArrayUtils.contains(new String[]{"treessfield", "treessareafield"}, xtype)) {
                    String[] configs = columnField.getStr("RESOURCEFIELD_CONFIGINFO", "").split(ArrayUtils.SPLIT);
                    if (configs.length > 0) {
                        String ddCode = configs[0];
                        DynaBean dic = metaService.selectOne("JE_CORE_DICTIONARY",
                                ConditionsWrapper.builder().apply(" DICTIONARY_DDTYPE IN ('LIST','TREE') AND DICTIONARY_DDCODE={0}", ddCode));
                        if (dic != null) {
                            dataField.set("DATAFIELD_XTYPE", "cbbfield");
                            dataField.set("DATAFIELD_CONFIGINFO", columnField.getStr("RESOURCEFIELD_CONFIGINFO"));
                        } else {
                            dataField.set("DATAFIELD_XTYPE", "textfield");
                        }
                    } else {
                        dataField.set("DATAFIELD_XTYPE", "textfield");
                    }
                } else {
                    dataField.set("DATAFIELD_XTYPE", "textfield");
                }
            }
            dataField.set("DATAFIELD_WIDTH", columnField.getStr("RESOURCECOLUMN_WIDTH"));
            dataField.set("DATAFIELD_VALUE", columnField.getStr("RESOURCEFIELD_VALUE"));
            dataField.set("DATAFIELD_SSDBT", columnField.getStr("RESOURCECOLUMN_MORECOLUMNNAME"));
            dataField.set("DATAFIELD_XLK", "0");
            dataField.set("DATAFIELD_EMPTY", "0");
            if ("0".equals(columnField.getStr("RESOURCEFIELD_ALLOWBLANK"))) {
                dataField.set("DATAFIELD_EMPTY", "1");
            }
            dataField.set("DATAFIELD_HIDDEN", columnField.getStr("RESOURCECOLUMN_HIDDEN"));
            dataField.set("JE_SYS_DATATEMPLATE_ID", pkValue);
            commonService.buildModelCreateInfo(dataField);
            metaService.insert(dataField);
        }
        return BaseRespResult.successResult(null,"导入成功!");
    }

    /**
     * 清空隐藏
     *
     * @param param
     */
    @RequestMapping(value = "clearHidden", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult clearHidden(BaseMethodArgument param) {
        String pkValue = param.getPkValue();
        if (StringUtil.isNotEmpty(pkValue)) {
            metaService.executeSql("DELETE FROM JE_SYS_DATAFIELD WHERE JE_SYS_DATATEMPLATE_ID={0} AND DATAFIELD_HIDDEN='1'", pkValue);
            return BaseRespResult.successResult(null,"操作成功!");
        } else {
            return BaseRespResult.errorResult("删除出错，请联系管理员!");
        }
    }

    /**
     * 应用表
     *
     * @param param
     */
    @RequestMapping(value = "applyFunc", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult applyFunc(BaseMethodArgument param,HttpServletRequest request) {
        DynaBean funcInfo = metaService.selectOne("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder().apply("FUNCINFO_FUNCCODE='JE_SYS_DATATEMPLATE' AND FUNCINFO_NODEINFOTYPE='FUNC'"),
                "JE_CORE_FUNCINFO_ID,FUNCINFO_FUNCNAME,FUNCINFO_FUNCCODE");
        List<DynaBean> buttons = metaService.select("JE_CORE_RESOURCEBUTTON",
                ConditionsWrapper.builder().apply("RESOURCEBUTTON_FUNCINFO_ID={0} AND RESOURCEBUTTON_CODE IN ('downloadDataBtn','implDataBtn')", funcInfo.getStr("JE_CORE_FUNCINFO_ID")));
        String funcId = request.getParameter("funcId");
        String templateId = request.getParameter("templateId");
        Long count = metaService.countBySql(
                ConditionsWrapper.builder().table("JE_CORE_RESOURCEBUTTON")
                        .apply("RESOURCEBUTTON_FUNCINFO_ID={0} AND RESOURCEBUTTON_CODE IN ('downloadDataBtn','implDataBtn')", funcId));
        if (count > 0) {
            return BaseRespResult.errorResult("功能已有模版按钮，请先删除后应用!");
        }
        for (DynaBean button : buttons) {
            button.set("RESOURCEBUTTON_FUNCINFO_ID", funcId);
            button.set("JE_CORE_RESOURCEBUTTON_ID", null);
            String jsListener = button.getStr("RESOURCEBUTTON_JSLISTENER", "");
            jsListener = jsListener.replace("_JEREPLACEPKVALUE_", templateId);
            button.set("RESOURCEBUTTON_JSLISTENER", jsListener);
            button.set("RESOURCEBUTTON_DISABLED", "0");
            button.set("SY_ORDERINDEX", "0");
            commonService.buildModelCreateInfo(button);
            metaService.insert(button);
        }
        return BaseRespResult.successResult(null,"应用成功,请查看功能按钮信息!");
    }


}
